package cn.imvc.app.models;

import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.List;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.web.util.matcher.RequestMatcher;
import org.springframework.stereotype.Service;

import cn.imvc.app.entities.Seller;
import cn.imvc.app.entities.User;
import cn.imvc.app.entities.UserSeller;
import cn.imvc.app.repositories.UserSellerRespository;
import cn.imvc.core.ModelUtil;
import cn.imvc.data.domain.ViewRequest;
import cn.imvc.data.util.PageableUtil;
/**
 * 
 * @author zhanghy
 * @date 2016年8月16日下午3:29:44
 *
 */
@Service
public class UserSellerModelImpl implements UserSellerModel{
	
	@Autowired
	UserSellerRespository userSellerRespository;
	@Autowired
	UserModel userModel;

	public LinkedHashMap<RequestMatcher, Collection<ConfigAttribute>> getRequestMap() {
		return null;
	}

	public Page<UserSeller> find(ViewRequest viewRequest) {
		
		return userSellerRespository.findAll(ModelUtil.OrderByIdDesc(viewRequest));
	}

	public UserSeller get(int id) {
		
		return userSellerRespository.getOne(id);
	}

	public UserSeller save(UserSeller userSeller){
		
		return userSellerRespository.saveAndFlush(userSeller);
	}

	public UserSeller update(int id,UserSeller userSeller){
		UserSeller loadUserSeller = userSellerRespository.getOne(id);
		BeanUtils.copyProperties(userSeller, loadUserSeller, new String[]{"id"});
		return userSellerRespository.saveAndFlush(loadUserSeller);
	}

	public void delete(int id) {
		userSellerRespository.delete(id);
		
	}

	public void deleteBatch(int[] ids) {
		for (int id : ids) {
			userSellerRespository.delete(id);
		}
		
	}

	public List<UserSeller> findByUserId(int userId) {
		return userSellerRespository.findByUserId(userId);
	}

	public Page<Object[]> findObjectPage(int sellerId,ViewRequest viewRequest) {
		
		String sql = "select s.id as a,l.id as b,l.name,u.id as c,u.username as d from user_seller s left join user u on s.userId = u.id left join seller l on s.sellerId=l.id where l.id = "+sellerId;
		viewRequest = ModelUtil.OrderByIdDesc(viewRequest);
		PageRequest pageRequest = new PageRequest(viewRequest.getPage(), viewRequest.getSize());
		return userSellerRespository.findAllSql(sql, pageRequest);
	}

	@Override
	public List<UserSeller> getUserSellersByCurUser() {
		User user = userModel.getSessionUser();
		Integer userId = user.getId();
		return findByUserId(userId);
	}


}
